#!/usr/bin/env bash
#! Encoding UTF-8
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
clear;

[[ -z ${LOG_PATH} ]] \
  && LOG_PATH="${HOME}/log"
[[ ! -d ${LOG_PATH} ]] \
  && mkdir -p ${LOG_PATH}

SENDER=$1 #发件人
RECIVER=$2 #收件人
SUJECT="test send mail" #主题
MAIL_TEXT="I can not send mail to you , so test send mail whit telnet."    #邮件内容文件

if [ "$#" -lt 2 ] ; then
   echo "Usage: $0 mailsender@doamin.com mailrecieve@domain.com"
   exit 2
fi
#=====================================================
#       DNS检测,分别检测MX记录和SPF记录.
#=====================================================
dns_check(){
  DOMAIN_NAME=$1
  SPF_CHECK=$(dig txt ${DOMAIN_NAME} +short)
  MX_CHECK=$(dig mx ${DOMAIN_NAME} +short| awk '{print $NF}')
  echo -e "$(date +'%F %H:%M:%S') -info ：=== \033[0;31;1m${DOMAIN_NAME}\033[0m === is check =========" 
cat <<eof
------- "records 'SPF'" ----
${SPF_CHECK:-None}
------- "records 'MX'" -----
${MX_CHECK:-None}
++++++++++++++++++++++++++++
eof
}

send_mailto(){
(sleep 6
echo "helo ${SENDER_DOMAIN}"
sleep 3
echo "mail from:<${SENDER}>"
sleep 3
echo "rcpt to:<${RECIVER}>"
sleep 5
echo "data"
sleep 5
echo "From: <${SENDER}>"
sleep 1
echo "To: <${RECIVER}>"
sleep 1
echo "Subject: ${SUJECT}"
sleep 3
echo ""
echo "${MAIL_TEXT}"
sleep 2
#echo "."
sleep 5 ) | openssl s_client -starttls smtp -connect $1:25 -crlf -ign_eof
}

SENDER_DOMAIN=$(echo ${SENDER} |awk '{print substr($0,index($0,"@")+1,length($0))}')
dns_check ${SENDER_DOMAIN}
RECIVER_DOMAIN=$(echo ${RECIVER} |awk '{print substr($0,index($0,"@")+1,length($0))}')
dns_check ${RECIVER_DOMAIN}
if [[ -n $3 ]] ; then
  MX_CHECK=$3
fi
RECIVER_MX_LISTS=${MX_CHECK}

TMP_FIFO_FILE="/tmp/$$.fifo" \
  && mkfifo "${TMP_FIFO_FILE}" \
  && exec 6<>"${TMP_FIFO_FILE}" \
  && rm "${TMP_FIFO_FILE}"

for VAR in ${RECIVER_MX_LISTS};do
  echo
done >&6
for VAR in ${RECIVER_MX_LISTS};do
  read -u6
  {
  echo -e "======== TEST : \033[0;31;1m${VAR}\033[0m =========" > ${LOG_PATH}/${VAR}_$(date +%F).log
  send_mailto ${VAR} 2>&1 >>${LOG_PATH}/${VAR}_$(date +%F).log
  echo >&6
  } &
done
wait
exec 6>&-
for VAR in ${RECIVER_MX_LISTS};do
  cat ${LOG_PATH}/${VAR}_$(date +%F).log
done